# coding=utf-8
import urllib2
import os
import sys
import time
from selenium.webdriver.support.select import Select
from selenium import webdriver
from image_handler import ImageHandler

browser = webdriver.PhantomJS()

base_url = 'http://www.930mh.com/'


def get_img_url(url):
    try:
        browser.get(url)
        div = browser.find_element_by_id('images')
        img = div.find_element_by_tag_name('img')
        return img.get_attribute('src')
    finally:
        print 'save image finish'


def save_chapter(folder, chapter_url):
    print 'retrieving chapter ' + folder

    if not os.path.exists(folder):
        os.makedirs(folder)
    else:
        print 'already exists next'
        return

    browser.get(chapter_url)
    select = Select(browser.find_element_by_id('page_select'))
    count = len(select.options)

    for i in range(1, count):
        print 'retrieving image:' + str(i)
        url = '{0}#p={1}'.format(chapter_url, i)
        ImageHandler.save_image(file_path=u'{0}/{1}.jpg'.format(folder, i), image_url=get_img_url(url))
        time.sleep(2)


def main():
    if len(sys.argv) < 2:
        print 'please specify page'
        return

    url = base_url + 'manhua/' + sys.argv[1] + '/'
    print 'retrieving page:' + url

    browser.get(url)
    ul = browser.find_element_by_id('chapter-list-1')
    lis = ul.find_elements_by_tag_name('li')

    chapter_infos = {}

    for li in lis:
        chapter_infos[li.find_element_by_class_name('list_con_zj').get_property('text')] = li.find_element_by_tag_name('a').get_attribute('href')

    for key in chapter_infos.keys():
        save_chapter(folder=key, chapter_url=chapter_infos.get(key))
        time.sleep(2)


if __name__ == '__main__':
    main()
